package likouJava;

public class 岛屿数量 {
    public int numIslands(char[][] grid) {
        if(grid == null || grid.length == 0) return  0;

        int row = grid.length, col = grid[0].length;
        int count = 0;

        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                if (grid[i][j] == '1'){
                    count++;
                    dfs(grid,i,j,row,col);
                }
            }
        }
        return count;

    }

    private void dfs(char[][] grid, int i, int j, int row, int col) {
        //边界检测
        if (i < 0 || i >= row || j < 0 || j >= col || grid[i][j] == '0'){
            return;
        }

        //标记已经访问过的陆地
        grid[i][j] = '0';

        //递归访问上下左右的邻居
        dfs(grid, i + 1, j, row, col);    //向上
        dfs(grid, i - 1, j, row, col);    //向下
        dfs(grid, i, j + 1, row, col);    //向右
        dfs(grid, i, j - 1, row, col);    //向左
    }

}
